import { KorNameEditParams as Params } from '@swda/configs/params'


// private class
function TextBox() {
    this.initialize.apply(this, arguments);
};

//===========================================================================
// Private Members
//===========================================================================
var original_Input_shouldPreventDefault = Input._shouldPreventDefault;
var dialog_Input_shouldPreventDefault = function (keyCode) {
    switch (keyCode) {
        case 33:    // pageup
        case 34:    // pagedown
        case 37:    // left arrow
        case 38:    // up arrow
        case 39:    // right arrow
        case 40:    // down arrow
            return true;
    }
    return false;
};

//===========================================================================
// TextBox Class
//===========================================================================
TextBox.BACK_SPACE = 8;
TextBox.ENTER = 13;
TextBox.IS_NOT_CHAR = 32;
TextBox.KEYS_ARRAY = 255;

TextBox.prototype.initialize = function (_editWindow) {
    this._editWindow = _editWindow;
    this.createTextBox();
    this.startToConvertInput();
    this.blur();
};



TextBox.prototype.createTextBox = function () {
    this._textBox = document.createElement('input');
    this._textBox.type = "text";
    this._textBox.id = "textBox";
    this._textBox.style.zIndex = 8;
    this._textBox.style.position = 'absolute';
    this._textBox.style.top = 0;
    this._textBox.style.left = 0;
    this._textBox.style.right = 0;
    this._textBox.style.bottom = 0;
    // For decreasing a layout size
    if (Utils.isMobileDevice()) {
        this._textBox.style.background = "transparent";
        this._textBox.style.color = "none";
        this._textBox.style.border = "none";
        this._textBox.style.width = "70%";
        this._textBox.style.height = "5%";
        this._textBox.style.outline = "none";
        this._textBox.style.overflow = "hidden";
    } else {
        this._textBox.style.opacity = 0;
    }

    this._textBox.style.width = "1px";
    this._textBox.style.height = "1px";
    this._textBox.onkeydown = this.onKeyDown.bind(this);
    document.body.appendChild(this._textBox);
};



TextBox.prototype.startToConvertInput = function () {
    Input._shouldPreventDefault = dialog_Input_shouldPreventDefault;
};


TextBox.prototype.startToOriginalInput = function () {
    Input._shouldPreventDefault = original_Input_shouldPreventDefault;
};


TextBox.prototype.setEvent = function (func) {
    this._textBox.onchange = func;
};



TextBox.prototype.removeEvent = function () {
    this._textBox.onchange = null;
};



TextBox.prototype.removeElement = function () {
    this._textBox.style.display = 'none';
    document.body.removeChild(this._textBox);
};



TextBox.prototype.terminateTextBox = function () {
    this.removeEvent();
    this.removeElement();
    this.startToOriginalInput();
};



TextBox.prototype.onKeyDown = function (e) {
    var keyCode = e.which;
    // TODO: It may be performance down because recalculating a style and layout.
    // link : https://goo.gl/29Q9wD
    this.getFocus();
    if (keyCode < TextBox.IS_NOT_CHAR) {
        if (keyCode === TextBox.BACK_SPACE) {
            // if(e && e.preventDefault) e.preventDefault();
        } else if (keyCode === TextBox.ENTER) {
            if (this.getTextLength() <= 0) {
                e.preventDefault();
                // console.error("아무 글자도 입력하지 않았습니다");
            }
        }
    } else if (keyCode < TextBox.KEYS_ARRAY) {
        //
    }
}

TextBox.prototype.getTextLength = function () {
    return this._textBox.value.length;
};

TextBox.prototype.getMaxLength = function () {
    return this._editWindow._maxLength;
};

TextBox.prototype.backSpace = function () {
    this._editWindow._name = this._editWindow._name.slice(0, this._textBox.value.length - 1);
    this._editWindow._index = this._textBox.value.length;
    this._textBox.value = this._editWindow._name;
    this._editWindow.refresh();
};

TextBox.prototype.refreshNameEdit = function () {
    
    if (this.getTextLength() > this._editWindow._maxLength) {
        this._textBox.value = this._textBox.value.toString().slice(0, this._editWindow._maxLength)
        
    }
    // 确保光标位置一致（感谢AI）
    //console.log('Cursor Position:',this._textBox.selectionStart)
    let length = this._textBox.value.length;
    this._textBox.setSelectionRange(length, length)

    this._editWindow._name = this._textBox.value.toString();
    this._editWindow._index = this._editWindow._name.length || 0;
    this._editWindow.refresh();
};

TextBox.prototype.update = function () {
    this.refreshNameEdit();
};



TextBox.prototype.getFocus = function () {
    this._textBox.focus();
};



TextBox.prototype.blur = function () {
    this._textBox.blur();
};



TextBox.prototype.terminate = function () {
    this.terminateTextBox();
};



TextBox.prototype.setDefaultName = function (name) {
    this._textBox.value = name || '';
    this.refreshNameEdit();
};

//===========================================================================
// Window_NameEdit Class 【头像窗口】
//===========================================================================
function Window_NamePortrait() {
    this.initialize.apply(this, arguments);
}

Window_NamePortrait.prototype = Object.create(Window_Base.prototype);
Window_NamePortrait.prototype.constructor = Window_NamePortrait;

Window_NamePortrait.prototype.initialize = function (actor) {
    var width = 450 + 48;
    var height = Graphics.boxHeight + 48;
    Window_Base.prototype.initialize.call(this, -24, -24, width, height);
    this._actor = actor;
    this.opacity = 0;
    //this.reservePortraitImages();
    ImageManager.reservePortrait(actor);
    this.refresh();


};


Window_NamePortrait.prototype.setActor = function (actor) {
    if (this._actor !== actor) {
        this._actor = actor;
        this.refresh();
    }
};

Window_NamePortrait.prototype.refresh = function () {
    this.contents.clear();
    if (this._actor) {
        this.drawPortrait();
    }
};

Window_NamePortrait.prototype.drawPortrait = function () {
    this.SWDA_drawActorPortrait(this._actor, 0, 0);
    //this.drawActorName(this._actor, 114, 608);
};

//===========================================================================
// Window_NameEdit Class 【编辑姓名窗口】
//===========================================================================

function Window_KorNameEdit() {
    this.initialize.apply(this, arguments);
}

Window_KorNameEdit.prototype = Object.create(Window_NameEdit.prototype);
Window_KorNameEdit.prototype.constructor = Window_KorNameEdit;
Window_KorNameEdit.prototype.initialize = function (actor, maxLength) {
    Window_NameEdit.prototype.initialize.call(this, actor, maxLength);
    this.x = 568 + 48;
};


/*
// 默认字体
Window_KorNameEdit.prototype.standardFontFace = function() {
  if ($gameSystem.isChinese()) {
      return Params.fonts.ChineseFonts;
  } else if ($gameSystem.isKorean()) {
      return Params.fonts.KoreanFonts;
  } else {
      return Params.fonts.DefaultFonts;
  }

};
*/

// 字符宽度匹配系统
Window_KorNameEdit.prototype.charWidth = function () {
    // TODO: This code has a bug that 'navigator.language' has always returned
    // 'en-US' due to a bug of crosswalk-10.39.235.16 xwalk library.
    var text = Params.defaultCharWidth;
    if (navigator.language.match(/^zh/)) {
        // isChinese
        text = '\u4E00';
    } else if (navigator.language.match(/^ko/)) { // isKorean
        text = '\uAC00';
    } else if (navigator.language.match(/^ja/)) { // isJapanese
        text = '\u3042';
    }
    return this.textWidth(text);
};




Window_KorNameEdit.prototype.itemRect = function (index) {
    return {
        x: this.left() + index * this.charWidth(),
        y: this.fittingHeight(1),
        width: this.charWidth(),
        height: this.lineHeight()
    };
};


Window_KorNameEdit.prototype.windowWidth = function () {
    return 480;
};



Window_KorNameEdit.prototype.drawChar = function (index) {
    var rect = this.itemRect(index);
    this.resetTextColor();
    /*
    this.contents.outlineWidth = Params.outlineWidth;
    this.contents.outlineColor = Params.outlineColor;
    this.contents.fontColor = Params.fontColor;
    */
    this.drawText(this._name[index] || '', rect.x, rect.y)
};
/*
Window_KorNameEdit.prototype.standardFontSize = function() {
    return Params.standardFontSize;
};
*/
Window_KorNameEdit.prototype.left = function () {
    return 96;
}


Window_KorNameEdit.prototype.refresh = function () {
    this.contents.clear();

    this.drawActorCharacter(this._actor, 48, 120);
    if(this.active){
        this.drawText(Params.askText, this.left(), 24, this.width);
    }else{
        this.drawText("该角色的名字是：", this.left(), 24, this.width);
    }
    var rect = this.itemRect(Math.max(this._index - 1, 0));
    if(this.active){
        for (var i = 0; i < this._maxLength; i++) {
            this.drawUnderline(i);
        }
    }
    for (var j = 0; j < this._name.length; j++) {
        this.drawChar(j);
    }

    if(this.active){
        if (this._index === 0) {
            this.setCursorRect(rect.x, rect.y, 1, rect.height);
        } else {
            this.setCursorRect(rect.x + (rect.width - 1), rect.y, 1, rect.height);
        }
    }else{
        this.setCursorRect(0, 0, 0, 0);
    }
};

Window_KorNameEdit.prototype.drawUnderline = function(index) {
    var rect = this.underlineRect(index);
    var color = this.underlineColor();
    this.contents.paintOpacity = 128;
    this.contents.fillRect(rect.x, rect.y, rect.width, rect.height, color);
    this.contents.paintOpacity = 255;
};

//===========================================================================
// Window_NameOK【修改，跳过】
//===========================================================================
function Window_KorNameCommand() {
    this.initialize.apply(this, arguments);
}
Window_KorNameCommand.prototype = Object.create(SWDA_Window_Command_4Arrows.prototype);//SWDA
Window_KorNameCommand.prototype.constructor = Window_KorNameCommand;
Window_KorNameCommand.prototype.initialize = function () {
    this.clearCommandList();
    this.makeCommandList();
    var width = this.windowWidth();
    var height = this.windowHeight();
    SWDA_Window_Command_4Arrows.prototype.initialize.call(this, -24, -24, width, height);//SWDA
    this.createButtons(Params.nameButtonImage, 808, 504);//SWDA
    this.updatePlacement();
    this.refresh();
    this.select(1);
    this.activate();
};

Window_KorNameCommand.prototype.makeCommandList = function () {
    this.addCommand('', '', false);//SWDA
    this.addCommand(Params.defaultCancelButtonName, 'quit');
    this.addCommand('', '', false);//SWDA
    this.addCommand(Params.defaultEditButtonName, 'edit');
};


Window_KorNameCommand.prototype.updatePlacement = function () {
    this.x = 0;
    this.y = 0;
};

//===========================================================================
// Window_NameOK【可，否】
//===========================================================================
function Window_KorNameConfirm() {
    this.initialize.apply(this, arguments);
}
Window_KorNameConfirm.prototype = Object.create(SWDA_Window_Command_4Arrows.prototype);//SWDA
Window_KorNameConfirm.prototype.constructor = Window_KorNameConfirm;
Window_KorNameConfirm.prototype.initialize = function () {
    this.clearCommandList();
    this.makeCommandList();
    var width = this.windowWidth();
    var height = this.windowHeight();
    SWDA_Window_Command_4Arrows.prototype.initialize.call(this, -24, -24, width, height);//SWDA
    this.createButtons("MenuButton_YN", 808, 504);//SWDA
    this.updatePlacement();
    this.refresh();
    this.select(1);
    this.activate();
};

Window_KorNameConfirm.prototype.makeCommandList = function () {
    this.addCommand('', '', false);//SWDA
    this.addCommand(Params.defaultOKButtonName, 'ok');
    this.addCommand('', '', false);//SWDA
    this.addCommand(Params.defaultCancelButtonName, 'cancel');
};


Window_KorNameConfirm.prototype.updatePlacement = function () {
    this.x = 0;
    this.y = 0;
};



//===========================================================================
// Scene_Name Class
//===========================================================================
function Scene_KorName() {
    this.initialize.apply(this, arguments);
}

Scene_KorName.prototype = Object.create(Scene_Name.prototype);
Scene_KorName.prototype.constructor = Scene_KorName;
Scene_KorName.prototype.initialize = function () {
    if (Imported.RS_HangulBitmapText) {
        $gameTemp.setHangulBitmapText(false);
    }
    Scene_Name.prototype.initialize.call(this);
};


Scene_KorName.prototype.createBackground = function () {
    var bitmap = SceneManager.backgroundBitmap();
    var customBackgroundImageName = Params.defaultBackground;
    this._backgroundSprite = new Sprite();
    this._backgroundSprite.bitmap = bitmap;
    this.addChild(this._backgroundSprite);
    if (!(customBackgroundImageName === 'auto')) {
        this._backgroundSprite2 = new Sprite();
        this._backgroundSprite2.bitmap = ImageManager.loadBitmap('img/system/UI/', customBackgroundImageName || '');
        this.addChild(this._backgroundSprite2);
    }

};


Scene_KorName.prototype.update = function () {

    if (this._commandWindow.active) {
        this._textBox.blur();
    } else {
        this._textBox.getFocus();
    }
    this._textBox.update();
    Scene_MenuBase.prototype.update.call(this);
    this._commandWindow.refresh();
};

Scene_KorName.prototype.terminate = function () {
    Scene_MenuBase.prototype.terminate.call(this);
    this._textBox.terminate();
    if (Imported.RS_HangulBitmapText) {
        $gameTemp.setHangulBitmapText(RS.HangulBitmapText.Params.tempInit);
    }
};

Scene_KorName.prototype.start = function () {
    Scene_Name.prototype.start.call(this);
    this.startFadeIn(this.fadeSpeed());
    this._portraitWindow.refresh();
};

Scene_KorName.prototype.create = function () {
    Scene_MenuBase.prototype.create.call(this);
    this._actor = $gameActors.actor(this._actorId);
    this.createCommandWindow();
    this.createConfirmWindow();
    this.createPortraitWindow();
    this.createEditWindow();
    this.createTextBox();

    //this._textBox.setEvent(this.onInputOk.bind(this));
    if (window.cordova && window.StatusBar) {
        window.StatusBar.show();
    }
};

Scene_KorName.prototype.createPortraitWindow = function () {
    this._portraitWindow = new Window_NamePortrait(this._actor);
    this.addWindow(this._portraitWindow);
};

Scene_KorName.prototype.createEditWindow = function () {
    this._editWindow = new Window_KorNameEdit(this._actor, this._maxLength);
    this.addWindow(this._editWindow);
};



Scene_KorName.prototype.createCommandWindow = function () {
    this._commandWindow = new Window_KorNameCommand();
    this._commandWindow.setHandler('quit', this.commandQuit.bind(this));
    this._commandWindow.setHandler('edit', this.commandEdit.bind(this));
    this.addWindow(this._commandWindow);
};

Scene_KorName.prototype.createConfirmWindow = function () {
    this._confirmWindow = new Window_KorNameConfirm();
    this._confirmWindow.setHandler('ok',     this.commandOk.bind(this));
    this._confirmWindow.setHandler('cancel', this.commandCancel.bind(this));
    this._confirmWindow.deactivate();
    this._confirmWindow.hide();
    this.addWindow(this._confirmWindow);
};

Scene_KorName.prototype.createTextBox = function () {
    this._textBox = new TextBox(this._editWindow);
    if (this._actor) this._textBox.setDefaultName(this._actor.name());
    if (Params.windowCenter === "true") {
        this._editWindow.y = Graphics.boxHeight / 2 - this._editWindow.height / 2;
    }
    this._editWindow.opacity = Params.opacity;
};


/**
 * 选择“可”指令：退出该命名界面
 * @method commandQuit
 */
Scene_KorName.prototype.commandQuit = function () {
    this._textBox.blur();
    if (window.cordova && window.StatusBar) {
        window.StatusBar.hide();
    }
    this.startFadeOut(this.fadeSpeed());
    this.popScene();
};

/**
 * 选择“修改”指令：开启命名修改
 * @method commandEdit
 */
Scene_KorName.prototype.commandEdit = function () {
    this._commandWindow.deactivate();
    this._commandWindow.hide();
    this._confirmWindow.selectSymbol('ok');
    this._confirmWindow.activate();
    this._confirmWindow.show();
    this._editWindow.activate();
    this._textBox.getFocus();
};

/**
 * 在修改名称时，选择“可”指令，若名称为空，则保持编辑界面。若已命名，则应用修改名称。
 * @method commandOk
 */
Scene_KorName.prototype.commandOk = function () {
    // 禁止命名为空格（感谢AI）
    if (this._editWindow._name === undefined || this._editWindow._name.trim() === '') {
        this.commandEdit();
        return;
    }
    this._editWindow.deactivate();
    this._commandWindow.selectSymbol('quit');
    this._commandWindow.activate();
    this._commandWindow.show();
    this._confirmWindow.deactivate();
    this._confirmWindow.hide();

    this._textBox.blur();
    Input.clear();
    
    if (window.cordova && window.StatusBar) {
        window.StatusBar.hide();
    }
    this._actor.setName(this._editWindow.name());
    
};

/**
 * 在修改名称时，选择“否”指令：重置名称
 * @method commandCancel
 */
Scene_KorName.prototype.commandCancel = function () {
    this._editWindow.deactivate();
    this._commandWindow.selectSymbol('quit');
    this._commandWindow.activate();
    this._commandWindow.show();
    this._confirmWindow.deactivate();
    this._confirmWindow.hide();

    this._textBox.blur();
    Input.clear();

    if (window.cordova && window.StatusBar) {
        window.StatusBar.hide();
    }

    this._textBox.setDefaultName(this._actor.name());
    this._textBox.refreshNameEdit();
};

// 名称修改时按确认键
/*
Scene_Name.prototype.onInputOk = function () {
    // Lose Focus
    //this._editWindow.deactivate();
    this._textBox.blur();
    // Select symbol.
    //this._commandWindow.selectSymbol('ok');
    //this._commandWindow.activate();
    Input.clear();
};
*/
//===========================================================================
// Game_Interpreter
//===========================================================================

// Name Input Processing
Game_Interpreter.prototype.command303 = function () {
    if (!$gameParty.inBattle()) {
        if ($dataActors[this._params[0]]) {
            SceneManager.push(Scene_KorName);
            SceneManager.prepareNextScene(this._params[0], this._params[1]);
        }
    }
    return true;
};


//===========================================================================
// Game_Interpreter
//===========================================================================

var alias_Game_Interpreter_pluginCommand = Game_Interpreter.prototype.pluginCommand;
Game_Interpreter.prototype.pluginCommand = function (command, args) {
    alias_Game_Interpreter_pluginCommand.call(this, command, args);
    if (command === "KNE") {
        switch (args[0]) {
            case 'width':
            case '폭':
                if (args[1] !== 'auto') {
                    Params.windowWidth = Number(args[1] || 580);
                } else {
                    Params.windowWidth = 'auto';
                }
                break;
            case 'center':
            case '중앙정렬':
                Params.windowCenter = String(args[1] || 'false');
                break;
            case 'outlineWidth':
            case '테두리크기':
                Params.outlineWidth = Number(args[1] || 1);
                break;
            case 'outlineColor':
            case '테두리색상':
                Params.outlineColor = String(args[1] || 'black');
                break;
            case 'fontColor':
            case '폰트색상':
                Params.fontColor = String(args[1] || 'white');
                break;
            case 'fontSize':
            case '폰트크기':
                Params.standardFontSize = Number(args[1] || 28);
                break;
            case 'opacity':
            case '투명도':
                var _opacity = Number(args[1] || 1);
                Params.opacity = _opacity.clamp(0, 255);
                break;
            case 'askText':
            case '텍스트':
                Params.askText = String(args.slice(1).join(""));
                break;
        }
    }
};